package com.xyzwps.example.stream;

import java.util.Objects;
import java.util.function.Predicate;

public class FilterOperator<T> implements Operator<T, T> {

    private final Predicate<T> predicateFn;

    public FilterOperator(Predicate<T> predicateFn) {
        this.predicateFn = Objects.requireNonNull(predicateFn);
    }

    @Override
    public Stream<T> handle(Stream<T> origin) {
        return new Stream<>() {
            @Override
            public Parcel<T> next() {
                while (true) {
                    var parcel = origin.next();
                    switch (parcel) {
                        case Parcel.Done<T> ignored:
                            return Parcel.done();
                        case Parcel.Failure<T> failure:
                            return Parcel.failed(failure.cause());
                        case Parcel.Delivery<T> delivery:
                            var v = delivery.value();
                            if (predicateFn.test(v)) {
                                return Parcel.deliver(v);
                            }
                            break;
                        default:
                            throw new RuntimeException("TODO: 未知 Parcel 类型");
                    }
                }
            }
        };
    }
}
